import { deleteKeyword, pageKeyword } from '@/services/api/api-datahub-keyword';
import { ModalForm } from '@ant-design/pro-components';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { useAccess } from '@umijs/max';
import { message, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import AddKeyword from './AddKeyword';
import EditKeyword from './EditKeyword';

interface TableKeywordProps {
  organization: {};
  onSaveSuccess: () => void;
}
const TableKeyword: React.FC<TableKeywordProps> = ({ organization, onSaveSuccess }) => {
  const [selectedAccountRowKeys, setSelectedAccountRowKeysState] = useState<React.Key[]>([]);

  const userRef = useRef<ActionType>();
  const access = useAccess();

  const columns: ProColumns<DatahubKeywordData.KeywordPage>[] = [
    {
      title: '名称',
      key: 'name',
      dataIndex: 'name',
      width: '180px',
    },
    {
      title: '类型',
      key: 'types',
      dataIndex: 'types',
      valueType: 'select',
      valueEnum: {
        1: { text: '人名', status: 'Error' },
        2: { text: '地域', status: 'Success' },
        3: { text: '机构', status: 'Error' },
        4: { text: '其他', status: 'Success' },
      },
      width: '100px',
      render(dom, entity, index, action, schema) {
        return entity.types.map((item) => (
          <Tag
            color={
              item.id === '1'
                ? '#f50'
                : item.id === '2'
                ? '#ffd591'
                : item.id === '3'
                ? 'orange'
                : '#2db7f5'
            }
          >
            {item.name}
          </Tag>
        ));
      },
    },

    {
      title: '操作',
      valueType: 'option',
      width: '70px',
      fixed: 'right',
      render: (_, row, index, action) => [
        <EditKeyword
          data={row}
          onRefurbish={() => {
            userRef.current?.reload();
          }}
        />,
        <ModalForm
          key={'delete_record_modal_form'}
          title="是否删除"
          trigger={<a key="delete_record_a"> 删除</a>}
          autoFocusFirstInput
          modalProps={{
            width: 400,
            destroyOnClose: true,
          }}
          onFinish={async (values) => {
            const response = await deleteKeyword({ id: row.id, organizationId: organization?.key });
            if (response.code === 0) {
              message.success('删除成功！');
              userRef.current?.reload();
              action?.reload();
              return true;
            }
          }}
        >
          该关键词将会被删除，是否确定
        </ModalForm>,
      ],
    },
  ];

  useEffect(() => {
    userRef.current?.reloadAndRest();
    console.log(organization, String(organization?.pos).length);
  }, [organization]);

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await pageKeyword({
      organizationId: organization?.key,
      ...params,
    });

    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  return (
    <ProTable<AdminAccountData.Account>
      // ghost
      // search={false}
      columns={columns}
      actionRef={userRef}
      request={request}
      sticky
      rowKey="id"
      tableLayout="fixed"
      dateFormatter="string"
      bordered
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 20,
      }}
      toolBarRender={() => [
        String(organization?.pos).length > 6 && organization?.key !== '0' && (
          <AddKeyword
            organization={organization}
            onRefurbish={() => {
              userRef.current?.reload();
              onSaveSuccess();
            }}
          />
        ),
      ]}
    />
  );
};
export default TableKeyword;
